package com.example.ASimpleWeb;
import java.io.*;

public class QueenP{
    int n;  //存储棋盘大小
    int[] res;  //棋盘
    int count=0;    //记录总方法数

    QueenP(int n){
        this.n=n;
        res=new int[n+1]; //创建n大小是数组
        //初始化结果
        for (int i = 0; i <= this.n; ++i) {
            res[i]=-1;
        }
    }

    //N皇后问题求解
    public void toSolve(int line){
        //一列列搜索
        for (int i = 1;i <= n; ++i){
            if (line != 1 && i == res[line-1]){
                continue;
            }
            boolean flag=true;
            for (int j = 1; j < line; ++j){
                if (i == res[j] || Math.abs(line-j) == Math.abs(i-res[j])){
                    flag = false;   //对于同一列同一对角线的拒绝
                    break;
                }
            }
            if (flag){
                res[line] = i; //记录下这行所对应的皇后的列数
                if (line == n)
                {
                    ++count;
                    //输出该处的棋盘局面
                    display(count);
                    return;
                }
                //若没放满则放下一行
                toSolve(line + 1);
                res[line] = -1;
            }
        }
    }

    public void display(int _count){
        System.out.println("第"+_count+"种解法:");
        //打印结果序列
        for (int i=1; i <= n; ++i){
            System.out.print(res[i]);
            System.out.print(' ');
        }
        System.out.println();
        //打印一个棋盘
        for (int i = 1; i <= n; ++i){
            for (int j =1; j <= n; ++j){
                System.out.print(j==res[i]?'@':'.');
                System.out.print(' ');
            }
            System.out.println();
        }
    }


    public static void main(String[] args){
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);

        boolean flag=true;
        int n=0;
        while (flag) {
            try {
                System.out.println("请输入棋盘的大小:");
                n = Integer.parseInt(br.readLine());  //读取键盘的输入数据输入
                n = Math.abs(n);
                flag=false;
            } catch (Exception e) {
                flag=true;
            }
        }
        QueenP queenP=new QueenP(n);
        System.out.println("以下为结果:");
        queenP.toSolve(1);
        if(queenP.count!=0){
            System.out.println("总共有"+queenP.count+"种解法");
        }else {
            System.out.println("无解");
        }
    }
}
